<template>
  <div class="system-role-container">
    <el-card shadow="hover">
      <div class="system-user-search mb10">
        <pageSearch :searchformConfig="searchConfig" @handleQueryClick="handleQueryClick"
          @handleResetClick="handleResetClick" @handleAddClick="onOpenAddRole">
        </pageSearch>
      </div>

      <el-table-plus row-key="path" :pagination="pagination" :data="state.tableData.data" :columns="columns" :total="pagination.total"
        @page-change="handlePageChange" @prev-click="handlePageChange" @next-click="handlePageChange"
        >
        <template #status="{ cellValue, row, column }">
          <el-tag class="ml-2" :type="row.status == 0 ? 'success' : 'danger'"
            :disable-transitions="true">{{row.status==0?'启用':'禁用'}}</el-tag>
        </template>

        <template #hidden="{ cellValue, row, column }">
          <el-tag class="ml-2" :type="row.hidden == 0 ? 'success' : 'danger'"
            :disable-transitions="true">{{row.hidden==0?'显示':'隐藏'}}</el-tag>
        </template>

        <template #handle="{ cellValue, row, column }">
          <el-button :type="row.status == 0 ? 'danger' : 'success'" text size="small"
            v-if="state.tableData.auth.disable"
              @click="handleDisEnd({ cellValue, row, column })">{{ row.status == 0 ? '禁用' : '启用' }}</el-button>
          <el-button type="primary" size="small" text @click="handleEdit({ cellValue, row, column })" v-if="state.tableData.auth.edit">编辑</el-button>
          <el-button type="danger" size="small" text @click="handleDel({ cellValue, row, column })" v-if="state.tableData.auth.delete">删除</el-button>
        </template>
        <template #handleTitle>操作</template>
      </el-table-plus>
    </el-card>
    <MenusForm ref="formRef" @on-load="handleQueryClick"/>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive,computed ,ref} from 'vue'
import usePag from '/@/utils/table'
import { IForm } from '/@/types/form/search'
import pageSearch from '/@/components/search/page-search.vue'
import { success, confirm, error } from '/@/utils/msg'
import { menusApi } from '/@/api/system/menus'
import {FormInstance} from 'element-plus'

import {checkAuth} from '/@/utils/authFunction'

import MenusForm from '/@/views/system/menus/form.vue'

interface TableDataState {
  tableData: {
    data: Array<any>,
    params: {
      id?: string
      keys: string
    },
    auth:any
  }
}

// 表格数据
const state = reactive<TableDataState>({
  tableData: {
    data: [],
    params: {
      id: '',
      keys: ''
    },
    auth:{
      disable:false,
      edit:false,
      add:false,
      delete:false
    }
  }
})

const formRef = ref()

// 分页设置
const { PagStore } = usePag()

// 分页
const pagination = reactive({ ...state.tableData.params, ...PagStore })


// 表头数据
const columns: any = [
  { label: "菜单名称", prop: "title", width: '140', "show-overflow-tooltip": true },
  { label: "路由路径", prop: "path" },
  { label: "组件路径", prop: "component", "show-overflow-tooltip": true ,width: '340'},
  { label: "菜单状态", prop: "status", slots: {customRender: "status"},width: '120'},
  { label: "是否显示", prop: "hidden", slots: {customRender: "hidden"},width: '120'},
  { label: "排序", prop: "sort" ,width: '100'},
  {
    label: "操作",
    fixed: "right",
    prop: "handle",
    width: "130",
    align: "right",
    slots: {
      customRender: "handle",
      customTitle: "handleTitle",
    },
  }
]


// 加载列表
const dataList = async () => {
  const { currentPage, pageSize } = { ...pagination }
  const param = { ...state.tableData.params, pageSize, currentPage }
  return await menusApi().dataList(param)
}

// 删除
const deleteRole = async (id:number) => {
  return await menusApi().delete(id)
}

// 初始化数据列表
const initTableData = async () => {
  const ds = await dataList()
  const { data, total } = { ...ds }
  pagination.total = total
  state.tableData.data = data
  state.tableData.auth.edit = checkAuth('admin/menus/detail')
  state.tableData.auth.disable = checkAuth('admin/menus/disenabled')
  state.tableData.auth.delete = checkAuth('admin/menus/delete')
}

// 页面加载时
onMounted(() => {
  initTableData()
})

const colAttrs = {
  align: "left",
  type:"expand",
  border:'border'
}

// 删除
const handleDel = async (a: any) => {
  confirm(`此操作将永久删除菜单：“${a.row.name}”，是否继续?`).then(async () => {
    const { code, msg } = await deleteRole(a.row.id)
    if (code == 0 || code == true) {
      success(msg)
      initTableData()
    }
  }).catch(() => { })
}

// 编辑
const handleEdit = (a: any) => {
  formRef.value.editDialog(a.row.id, '编辑')
}

// 选择页面重新加载
const handlePageChange = (a: any) => {
  pagination.currentPage = a.currentPage
  initTableData()
}

// 打开新增弹窗
const onOpenAddRole = (a: any) => {
  formRef.value.openDialog()
}

// 查询
const handleQueryClick = (value: any) => {
  state.tableData.params = { ...value }
  initTableData()
}

// 重置
const handleResetClick = () => {
  console.log('重置')
}

// 启用/禁用
const handleDisEnd = (a: any) => {
  confirm(`确认${a.row.status==0?'禁用':'启用'} ”${a.row.title}” 该操作?`).then(async()=>{
    const {code,msg} = await menusApi().disenabled({id:a.row.id})
    if ( code == 0 || code == true ) {
      success(msg)
      initTableData()
    } else {
      error(msg)
    }
  })
}

// 搜索配置
const searchConfig: IForm = {
  formItems: [
    { field: 'keys', type: 'input', label: '用户名', placeholder: '请输入 关键字' },
  ]
}
defineExpose({
  formRef
})
</script>
